var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
// 引入环境变量配置，区分不同环境
require("./utils/env");
var adminAuthMiddle = require("./middlewares/adminAuth");
var userAuthMiddle = require("./middlewares/userAuth");

// 后端路由
var admin_articlesRouter = require("./routes/admin/articles");
var admin_categoriesRouter = require("./routes/admin/categories");
var admin_coursesRouter = require("./routes/admin/courses");
var admin_usersRouter = require("./routes/admin/users");
var admin_chaptersRouter = require("./routes/admin/chapters");
var adminAuthRouter = require("./routes/admin/auth");
var admin_echartsRouter = require("./routes/admin/echarts");
var admin_filesRouter = require("./routes/admin/files");

// 前台路由
var indexRouter = require("./routes/index");
var authRouter = require("./routes/auth");
var likeRouter = require("./routes/like");
var categoriesRouter = require("./routes/categories");
var coursesRouter = require("./routes/courses");
var filesRouter = require("./routes/files");

var app = express();
// const crypto = require('crypto')
// // dev环境、prod环境各自生成32随机码作为密钥
// const jwt_secket_random32 = crypto.randomBytes(32).toString('hex')
// console.log('secret', jwt_secket_random32)

const cors = require("cors");
app.use(
  cors({
    // 加上本地调试、生产的域名地址，即可解决跨域
    origin: ["http://127.0.0.1:5500", "http://localhost:5500"],
    // credentials: true,
    // methods: "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
    // preflightContinue: false,
    // optionsSuccessStatus: 204
  })
);

app.use(logger("dev"));
/**
 * express.json - 中间件
 * application/json 去解析json格式的数据
 * 在req.body中获取
 */
app.use(express.json());
/**
 * express.urlencoded -中间件
 * application/x-www-form-urlencoded 去解析html表单原生提交的数据，
 * extended: false 表示使用系统模块querystring来处理，能解析浅层的数据类型如字符串和数组等，而true时表示使用第三方模块qs来处理，可解析出嵌套的对象。
 * 在req.body中获取
 */
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// 后端路由
app.use("/users", adminAuthMiddle, admin_usersRouter);
app.use("/admin/articles", adminAuthMiddle, admin_articlesRouter);
app.use("/admin/categories", adminAuthMiddle, admin_categoriesRouter);
app.use("/admin/courses", adminAuthMiddle, admin_coursesRouter);
app.use("/admin/users", adminAuthMiddle, admin_usersRouter);
app.use("/admin/chapters", adminAuthMiddle, admin_chaptersRouter);
app.use("/admin/auth", adminAuthRouter);
app.use("/admin/echarts", adminAuthMiddle, admin_echartsRouter);
app.use("/admin/files", adminAuthMiddle, admin_filesRouter);

// 前台路由
app.use("/", indexRouter);
app.use("/auth", authRouter);
app.use("/like", userAuthMiddle, likeRouter);
app.use("/categories",userAuthMiddle, categoriesRouter);
app.use("/courses", userAuthMiddle, coursesRouter);
app.use("/files", userAuthMiddle, filesRouter);

module.exports = app;
